const express = require('express');

const checkTokenMiddleware = require('../../middleware/checkToken')
const AccountModel = require('../../module/accountModel');
const moment = require('moment')

const router = express.Router();


/* GET home page. */
router.get('/account', checkTokenMiddleware,function (req, res, next) {
  // let accounts = db.get('account').value()
  // console.log(accounts)
  console.log(req.user)
  AccountModel.find().sort({ time: -1 }).exec((err, data) => {
    if (err) {
      // res.status(500).send('查询失败')
      res.json({
        code: '1001',
        msg: '读取失败',
        data: null
      })
      return
    }
    // res.render('list', { accounts: data, moment: moment })
    res.json({
      code: '0000',
      msg: '读取成功',
      data: data
    })
  })
});

router.post('/account',checkTokenMiddleware, function (req, res, next) {
  // db.get('account').unshift({id:shortid.generate(),...req.body}).write()
  // console.log(req.body)
  AccountModel.create({
    ...req.body,
    time: moment(req.body.time).toDate()
  }, (err, data) => {
    if (err) {
      res.json({
        code: '1002',
        msg: '创建失败',
        data: null
      })
      return
    }
    res.json({
      code: '0000',
      msg: '创建成功',
      data: data
    })
  })
});

router.delete('/account/:id',checkTokenMiddleware, (req, res) => {
  let id = req.params.id
  // db.get('account').remove({id:id}).write()
  AccountModel.deleteOne({ _id: id }, (err, data) => {
    if (err) {
      res.json(
        {
          code: '1003',
          msg: '删除失败',
          data: null
        }
      )
      return
    }
    res.json({
      code: '0000',
      msg: '删除成功',
      data: data
    })
  })
})

router.get('/account/:id', checkTokenMiddleware,(req, res) => {
  let { id } = req.params
  AccountModel.findById(id, (err, data) => {
    if (err) {
      res.json({
        code: '1001',
        msg: '读取失败',
        data: null
      })
      return
    }
    res.json({
      code: '0000',
      msg: '读取成功',
      data: data
    })
  })
})

router.patch('/account/:id',checkTokenMiddleware, (req, res) => {
  let { id } = req.params
  console.log(req.body)
  AccountModel.updateOne({ _id: id }, req.body, (err, data) => {
    if (err) {
      res.json({
        code: '1005',
        msg: '更新失败',
        data: null
      })
      return
    }

    AccountModel.findById(id, (err, data) => {
      if (err) {
        res.json({
          code: '1001',
          msg: '读取失败',
          data: null
        })
        return
      }
      res.json({
        code: '0000',
        msg: '更新成功',
        data: data
      })
    })

  })
})

module.exports = router;
